<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath(); 
String strUserId = request.getSession().getAttribute("stxtUName").toString();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
  <head>
  	<style type="text/css" media="all">   
	    .allow-float {clear:none!important;} /* 允许该元素浮动 */  
	    .stop-float {clear:both!important;} /* 阻止该元素浮动 */  
	   	.icon-first {float:left;}   
	   	.icon-choosed {float:left;padding:5 0 0 5px;}
	    .icon-second {float:left;padding:0 0 0 20px;} 
	    .win-first {float:left;}   
	    .win-second {float:left;padding:0 0 0 20px;}   
	   	.standby-yes {float:left;}   
	    .standby-no {float:left;padding:0 0 0 20px;}   
	    .age-field {float:left;padding:0 0 0 58px;*padding:0 0 0 50px!important;*padding:0 0 0 50px;}   
	</style> 
  
    <base href="<%=basePath%>"> 
    <link rel="stylesheet" type="text/css" href="<%=path%>/js/ext/resources/css/ext-all.css">  
	<link rel="stylesheet" type="text/css" href="<%=path%>/js/ext/resources/css/edit-grid.css">  
	<script type="text/javascript" src="<%=path%>/js/ext/adapter/ext/ext-base.js"></script>
	<script type="text/javascript" src="<%=path%>/js/ext/ext-all.js"></script>
	<script type="text/javascript" src="<%=path%>/js/ext/DWRTreeLoader.js"></script> 
	<script type="text/javascript" src="<%=path%>/js/ext/query-dwr-proxy.js"></script>	
	<script type="text/javascript" src="<%=path%>/js/ext/ext-lang-zh_CN.js"></script>
	<script type="text/javascript" src="<%=path%>/js/system/TreeCheckNode.js"></script>
	<script type='text/javascript' src='/btsm/dwr/interface/JSystemWeb.js'></script>
	<script type='text/javascript' src='/btsm/dwr/engine.js'></script>
	<script type='text/javascript' src='/btsm/dwr/util.js'></script>	 
  </head>
<body> 	 
	<div id="roleTreeDIV" style="height:80%"/>
	<div id="roleGrid" style="width:100%;height:100%;align=center;"/>   
	<div id="userTreeDiv"/>
<script type="text/javascript">
var roleTreePanel;
var roleRoot;
var ds;
var sectionGrid;
var userWin;

Ext.onReady(function(){
	var viewport = new Ext.Viewport({
		layout:'border',
		frame:true,
		items:[ 
			{
				region: 'west',
				contentEl: 'roleTreeDIV',
				margins:'110 5 30 5',
				width:300,
				split: true,
				border: true	
			},
			{
				region: 'center',
				contentEl: 'roleGrid',
				margins:'110 30 30 5',
				split: true,
				border: true	
			}]
		});
	
	var btnAddRoles = new  Ext.Button({
					text:'创建角色',
					pressed:true,					 
					handler:createFiblerLink
				});
	var btnEditRoles = new  Ext.Button({
					text:'修改角色',
					pressed:true,					 
					handler:updateFiblerLink
				});	
	var btnDelRoles = new  Ext.Button({
					text:'删除角色',
					pressed:true,					 
					handler:doDelete
				});		
	var btnAddUsers = new  Ext.Button({
					text:'添加用户',
					pressed:true,					 
					handler:doAddUser
				});					
	
	
	var roleTreeDiv = Ext.get("roleTreeDiv");	   
    roleRoot = new Ext.tree.AsyncTreeNode({
           text: '系统角色', 
		   icon:'/btsm/js/ext/resources/images/user.gif',
           draggable:false, 
           id:'root'
     });	 
	roleTreePanel = new Ext.tree.TreePanel( {
		el : "roleTreeDiv",
		border : false,
		animate : true,
		autoHeight : true,
		height:roleTreeDiv.getComputedHeight(),
		rootVisible : true,
		autoScroll : true,
		containerScroll : true,
		loader : new Ext.tree.DWRTreeLoader( {
			dwrCall:JSystemWeb.findRoleTree,queryParam:{}
		}),
		root : roleRoot,
		tbar:[btnAddRoles,'-',btnEditRoles,'-',btnDelRoles]
	});
	roleTreePanel.render();
	roleRoot.expand(true,true);	
	roleTreePanel.on('click',function(node)
	{
		var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
		ds.on('beforeload', function() {
			  ds.baseParams = {
					ROLE_ID:selectNode.id, 
					limit:17
			  };
			});
		ds.load({params:{start:0,limit:17,ROLE_ID:selectNode.id}});	
		sectionGrid.setTitle("<"+selectNode.text+">用户");
	})
	
	
	
	
	var sm = new Ext.grid.CheckboxSelectionModel({singleSelect: true});	
	var recordType = Ext.data.Record.create([								
                			   {name: 'id', type: "string"}, 
							   {name: 'username', type: "string"}
                	     ]);

	var cm  = new Ext.grid.ColumnModel(
			[
				sm,	             
	            {header: "用户", width: 400, sortable: true, dataIndex: 'username',align:'left'}, 
				{header: "删除", width: 100, dataIndex: 'id',renderer: showDelete}					
			]
		);
	function showDelete(id)
	{
		return "<input type='button' value='删除' class='x-btn button' onclick='doDeleteUser(\"" + id + "\")'>";  
	}	
	ds = new Ext.data.Store({
        proxy: new Ext.data.DWRProxy(JSystemWeb.getUserListByRoleID, true),	
        reader: new Ext.data.ListRangeReader({
            totalProperty: 'totalSize',
            id: 'id'
        }, recordType),
        sortInfo:{field:'id', direction:'ASC'}// 排序信息
    });	
		
	var contentDiv = Ext.get("roleGrid");
	sectionGrid = new Ext.grid.GridPanel({
	    	el: 'roleGrid',	    	
	        ds: ds,
	        cm: cm, 
			title: '用户列表',
			width: contentDiv.getComputedWidth(),			
			height: contentDiv.getComputedHeight(), 
			border:false,
	        frame:true,
	        collapsible:false, 
	        enableDragDrop:false, 
			tbar: [
				btnAddUsers
				],			
			bbar: new Ext.PagingToolbar({
			        pageSize: 17,
			        store: ds,
			        displayInfo: true,
			        displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
			        emptyMsg: "没有记录"
			    })
					
					
				
	    });
    
	sectionGrid.render();  		
	ds.load({params:{start:0,limit:17,ROLE_ID:'0'}});
	
	

	//文件共享form				
	var FiblerLinkForm = function(){
			this.idTextField = {
					xtype : 'hidden',
					fieldLabel : "id",
					readOnly : true,
					name : "id"
				};
						
			this.NameTextField = {
					xtype : 'textfield',
					fieldLabel : "角色名称",
					allowBlank : false,
					name : "NAME",
					width:160,
					blankText :'请输入角色名称'	
			};					
			
			FiblerLinkForm.superclass.constructor.call(this, {
					bodyStyle : 'padding:5px 5px 0',
					frame : true,
					id: 'FiblerLinkForm',
					labelAlign: 'right',
					labelWidth:100,
					items : [this.idTextField, 
							 this.NameTextField
							 ]
				});	
	}	
	Ext.extend(FiblerLinkForm, Ext.form.FormPanel);
	//文件夹弹出win
	var FiberLinkWindow = function() {
		var _win = this;
		this.formPanel = new FiblerLinkForm();
		var _form = this.formPanel.getForm();
		FiberLinkWindow.superclass.constructor.call(this, {
			title : '创建/修改角色名称',
			width : 300,
			height : 120,
			resizable : true,
			plain : false,
			border : false,
			modal : true,
			autoScroll : false,
			layout : 'fit',
			closeAction : 'hide',
			items : this.formPanel,
			buttonAlign:'center',
			buttons : 
			[
				{	text : ' 保存',
					handler : function() 
					{
						if (_form.isValid()) 
						{
							var form = _form.getValues(false);
							RolesBO = {};
							RolesBO.NAME = form.NAME;
							RolesBO.id = form.id;						
							JSystemWeb.createRoles(RolesBO,function(data)
							{
								if(data)
	          					{
	          						_win.hide();
	          						Ext.Msg.alert('成功',"操作成功！",function()
	          						{
										roleRoot.reload();
										roleRoot.expand(true,true);	
	          						}); 
	          					}else
	          					{
	          						Ext.Msg.alert("失败","操作失败!");
	          					}																
							})
						}
					}
				},{
					text : '取消',
					handler : function() {
						_win.hide();
					},
					tooltip : '关闭对话框'
				}
			]	
		});
	}
	Ext.extend(FiberLinkWindow, Ext.Window);
	
	fiberLinkWindow = new FiberLinkWindow();
	function createFiblerLink()
	{
		var data = {'id':"",
					'NAME':""
					};
		var record = new Ext.data.Record(data);
		fiberLinkWindow.show();
		fiberLinkWindow.formPanel.getForm().loadRecord(record);				
	}
	
	function updateFiblerLink()
	{
		var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
		if(!selectNode || selectNode.id === "root")
		{			 
			Ext.Msg.alert("提示","请选择需要修改的角色!");
			return;			 
		}
		doDelete(selectNode.id);
	}
	
	function updateFiblerLink()
	{
		var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
		if(!selectNode || selectNode.id === "root")
		{
			Ext.Msg.alert("提示","请先选择需要修改的角色!");
			return;
		}
		var data = {'id':selectNode.id,
					'NAME':selectNode.text
					};
		var record = new Ext.data.Record(data);
		fiberLinkWindow.show();
		fiberLinkWindow.formPanel.getForm().loadRecord(record);	
	}
	 
	//父节点树
	var userTree = new Ext.tree.TreePanel( {
		el : "userTreeDiv",  
		loader :  new Ext.tree.DWRTreeLoader( {
				dwrCall:JSystemWeb.getUserListForRoles,queryParam:{}
			}),
		checkModel:'cascade',   //对树的级联多选 
		containerScroll: true,
		autoScroll:true,
		enableDD:false,
		enableDrag:false,
		enableDrop:false,
		rootVisible:false,
		header:true, 
		selModel:new Ext.tree.CheckNodeMultiSelectionModel(), 
		dropConfig: {appendOnly:true},
		toggleCheck : function(value){
			var cb = this.checkbox;
			if(cb){
				cb.checked = (value === undefined ? !cb.checked : value);
			}
		},
		getChecked : function(a, startNode){
			startNode = startNode || this.root;
			var r = [];
			var f = function(){
				if(this.attributes.checked){
					r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
				}
			}
			startNode.cascade(f);
			return r;
		}
	});

	
	var usertRoot = new Ext.tree.AsyncTreeNode({
		text: '用户', 
		draggable:false, // disable root node dragging
		id:'0'
	});
	userTree.setRootNode(usertRoot);

	 
	function doAddUser()
	{
		if(!userWin){
            userWin = new Ext.Window({ 
                layout:'fit',
                width:500,
                height:300,
                closeAction:'hide',
				modal : true,
                plain: true,   
				items:userTree,	
				buttonAlign :'center',
                buttons: [{
                    text:'保存', 
					handler: function()
					{
						var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
						if(!selectNode || selectNode.id === "root")
						{
							Ext.Msg.alert("提示","请先选择角色!");
							return;
						}
						var userNodeCode = "";	
						var checkedNodes = userTree.getChecked();	
						if(checkedNodes.length <= 0)
						{
							Ext.Msg.alert("提示","请选择要添加的用户!");
							return;
						}						
						for(var i=0;i<checkedNodes.length;i++)
						{
							var node = checkedNodes[i];
							if(userNodeCode == "")
							{
								userNodeCode = node.id;
							}else
							{
								userNodeCode = userNodeCode +";"+ node.id;
							}
						}
						JSystemWeb.addUserFromRole(userNodeCode,selectNode.id,function(value)
						{
							if(value)
							{
								Ext.Msg.alert('提示'," 设置成功!");
								ds.load({params:{start:0,limit:17,ROLE_ID:selectNode.id}});
							}else{
								Ext.Msg.alert('提示'," 设置失败!");
							}
						})
                        userWin.hide();
                    }
                },{
                    text: '取消',
                    handler: function(){
                        userWin.hide();
                    }
                }]
            });
        } 
		usertRoot.reload();
        userWin.show(this);

	}


	
})

function doDelete()
{
	var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
	if(!selectNode || selectNode.id === "root")
	{
		Ext.Msg.alert("提示","请先选择需要删除的角色!");
		return;
	}
	Ext.MessageBox.confirm('确认删除', '确认删除该角色信息?', 
	function(btn) {
		 if(btn == 'yes') // 选中了是按钮	
		 {	 
			JSystemWeb.deleteRoles(selectNode.id, function(data) {
				if(data) {							    	     		
					roleRoot.reload();
					roleRoot.expand(true,true);	
				}else 
				{
					Ext.Msg.alert("删除失败","数据删除失败!");
				}
			});
			
		 }
	});
}

function doDeleteUser(id)
{
	var selectNode = roleTreePanel.getSelectionModel().getSelectedNode();
	Ext.MessageBox.confirm('确认删除', '确认从该角色删除该用户?', 
	function(btn) {
		 if(btn == 'yes') // 选中了是按钮	
		 {	 
			JSystemWeb.deleteUserFromRole(id,selectNode.id, function(data) {
				if(data) {							    	     		
					 ds.load({params:{start:0,limit:17}});
				}else 
				{
					Ext.Msg.alert("删除失败","数据删除失败!");
				}
			});
			
		 }
	});
}



</script>
	
</body>
</html>